#include <stdio.h>
#include <error.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#include "pmsdr_com.h"

#define PMSDR_FILE "/tmp/PMSDRcommands"

static FILE *pmsdrFile = 0;

int pmsdr_init (void)
{
    int rc = 0;
    char *ep;

    // create the FIFO for commands
    system ("mkfifo "PMSDR_FILE);
    // start the server program
    system ("killall pmsdr");
    system ("pmsdr &");   // assume an correctly installed pmsdr package
    sleep (2);

    // Open the PMSDR command FIFO
	if ((ep = getenv("PMSDR_CMDPATH"))) {
		pmsdrFile = fopen( ep, "r+" );
		if ( pmsdrFile == NULL ) {
			perror( ep );
            rc = errno;
		}
	} else {
		printf( "::: Unable to get PMSDR_CMDPATH environment variable.\n"
				"Using default: %s\n", PMSDR_FILE );
		pmsdrFile = fopen( PMSDR_FILE, "r+" );
		if ( pmsdrFile == NULL ) {
			perror( PMSDR_FILE );
            rc = errno;
		}
	}

    return rc;
}

int pmsdr_setfreq (long newF)
{
   fprintf (stderr, "%s: %ld\n", __FUNCTION__, newF);
   if (pmsdrFile != 0) {
      fprintf ( pmsdrFile, "f %ld\n", newF );
      fflush  ( pmsdrFile );
   }
   return 0;
}

int pmsdr_terminate (void)
{
    //
    // terminate the pmsdr helper program
    //
    if ( pmsdrFile != NULL ) {
        fprintf ( pmsdrFile, "quit\n" );
        fflush  ( pmsdrFile );
 
        system ("rm "PMSDR_FILE);
        return 0;
    } else {
        return 1;
    }
}

